package com.ruoyi.manage.controller;

import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.manage.domain.CrInterviewAppointment;
import com.ruoyi.manage.service.ICrInterviewAppointmentService;

/**
 * 面试预约Controller
 * 
 * @author ruoyi
 * @date 2024-09-24
 */
@RestController
@RequestMapping("/campus/interviewAppointment")
public class CrInterviewAppointmentController extends BaseController
{
    @Autowired
    private ICrInterviewAppointmentService crInterviewAppointmentService;

    /**
     * 查询面试预约列表
     */
    @PreAuthorize("@ss.hasPermi('manage:appointment:list')")
    @GetMapping("/list")
    public TableDataInfo list(CrInterviewAppointment crInterviewAppointment)
    {
        startPage();
        List<CrInterviewAppointment> list = crInterviewAppointmentService.selectCrInterviewAppointmentList(crInterviewAppointment);
        return getDataTable(list);
    }

    /**
     * 导出面试预约列表
     */
    @PreAuthorize("@ss.hasPermi('manage:appointment:export')")
    @Log(title = "面试预约", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CrInterviewAppointment crInterviewAppointment)
    {
        List<CrInterviewAppointment> list = crInterviewAppointmentService.exportAppointments(crInterviewAppointment);
        ExcelUtil<CrInterviewAppointment> util = new ExcelUtil<CrInterviewAppointment>(CrInterviewAppointment.class);
        util.exportExcel(response, list, "面试预约数据");
    }

    /**
     * 获取面试预约详细信息
     */
    @PreAuthorize("@ss.hasPermi('manage:appointment:query')")
    @GetMapping(value = "/{appointmentId}")
    public AjaxResult getInfo(@PathVariable("appointmentId") Long appointmentId)
    {
        return success(crInterviewAppointmentService.selectCrInterviewAppointmentByAppointmentId(appointmentId));
    }

    /**
     * 新增面试预约
     */
    @PreAuthorize("@ss.hasPermi('manage:appointment:add')")
    @Log(title = "面试预约", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CrInterviewAppointment crInterviewAppointment)
    {
        return toAjax(crInterviewAppointmentService.insertCrInterviewAppointment(crInterviewAppointment));
    }

    /**
     * 修改面试预约
     */
    @PreAuthorize("@ss.hasPermi('manage:appointment:edit')")
    @Log(title = "面试预约", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CrInterviewAppointment crInterviewAppointment)
    {
        return toAjax(crInterviewAppointmentService.updateCrInterviewAppointment(crInterviewAppointment));
    }

    /**
     * 删除面试预约
     */
    @PreAuthorize("@ss.hasPermi('manage:appointment:remove')")
    @Log(title = "面试预约", businessType = BusinessType.DELETE)
	@DeleteMapping("/{appointmentIds}")
    public AjaxResult remove(@PathVariable Long[] appointmentIds)
    {
        return toAjax(crInterviewAppointmentService.deleteCrInterviewAppointmentByAppointmentIds(appointmentIds));
    }

    // ========== 业务相关接口 ==========

    /**
     * 学生预约面试
     */
    @PreAuthorize("@ss.hasPermi('manage:appointment:book') or @ss.hasPermi('campus:student:interview:book') or @ss.hasRole('student')")
    @Log(title = "预约面试", businessType = BusinessType.INSERT)
    @PostMapping("/book")
    public AjaxResult bookInterview(@RequestBody Map<String, Object> params)
    {
        Long studentId = Long.valueOf(params.get("studentId").toString());
        Long slotId = Long.valueOf(params.get("slotId").toString());
        Long applicationId = params.get("applicationId") != null ? 
            Long.valueOf(params.get("applicationId").toString()) : null;
        String remarks = (String) params.get("remarks");
        
        return toAjax(crInterviewAppointmentService.bookInterview(studentId, slotId, applicationId, remarks));
    }

    /**
     * 取消面试预约
     */
    @PreAuthorize("@ss.hasPermi('manage:appointment:cancel') or @ss.hasPermi('campus:student:interview:cancel') or @ss.hasRole('student')")
    @Log(title = "取消预约", businessType = BusinessType.UPDATE)
    @PutMapping("/cancel/{appointmentId}")
    public AjaxResult cancelAppointment(@PathVariable Long appointmentId, @RequestParam String reason)
    {
        Long userId = getUserId(); // 从当前登录用户获取
        return toAjax(crInterviewAppointmentService.cancelAppointment(appointmentId, userId, reason));
    }

    /**
     * 确认面试预约
     */
    @PreAuthorize("@ss.hasPermi('manage:appointment:confirm')")
    @Log(title = "确认预约", businessType = BusinessType.UPDATE)
    @PutMapping("/confirm/{appointmentId}")
    public AjaxResult confirmAppointment(@PathVariable Long appointmentId)
    {
        Long clubId = getUserId(); // 可根据实际情况调整获取方式
        return toAjax(crInterviewAppointmentService.confirmAppointment(appointmentId, clubId));
    }

    /**
     * 完成面试并评价
     */
    @PreAuthorize("@ss.hasPermi('manage:appointment:complete')")
    @Log(title = "完成面试", businessType = BusinessType.UPDATE)
    @PutMapping("/complete")
    public AjaxResult completeInterview(@RequestBody Map<String, Object> params)
    {
        Long appointmentId = Long.valueOf(params.get("appointmentId").toString());
        Long clubId = getUserId();
        String interviewResult = (String) params.get("interviewResult");
        Integer interviewScore = params.get("interviewScore") != null ? 
            Integer.valueOf(params.get("interviewScore").toString()) : null;
        String interviewFeedback = (String) params.get("interviewFeedback");
        
        return toAjax(crInterviewAppointmentService.completeInterview(
            appointmentId, clubId, interviewResult, interviewScore, interviewFeedback));
    }

    /**
     * 学生对面试进行反馈
     */
    @PreAuthorize("@ss.hasPermi('manage:appointment:feedback')")
    @Log(title = "提交面试反馈", businessType = BusinessType.UPDATE)
    @PutMapping("/feedback")
    public AjaxResult submitStudentFeedback(@RequestBody Map<String, Object> params)
    {
        Long appointmentId = Long.valueOf(params.get("appointmentId").toString());
        Long studentId = getUserId();
        String studentFeedback = (String) params.get("studentFeedback");
        Integer satisfactionRating = params.get("satisfactionRating") != null ? 
            Integer.valueOf(params.get("satisfactionRating").toString()) : null;
        
        return toAjax(crInterviewAppointmentService.submitStudentFeedback(
            appointmentId, studentId, studentFeedback, satisfactionRating));
    }

    /**
     * 重新安排面试时间
     */
    @PreAuthorize("@ss.hasPermi('manage:appointment:reschedule') or @ss.hasRole('student')")
    @Log(title = "重新安排面试", businessType = BusinessType.UPDATE)
    @PutMapping("/reschedule")
    public AjaxResult rescheduleAppointment(@RequestBody Map<String, Object> params)
    {
        Long appointmentId = Long.valueOf(params.get("appointmentId").toString());
        Long newSlotId = Long.valueOf(params.get("newSlotId").toString());
        String rescheduleReason = (String) params.get("rescheduleReason");
        
        return toAjax(crInterviewAppointmentService.rescheduleAppointment(appointmentId, newSlotId, rescheduleReason));
    }

    /**
     * 批量确认预约
     */
    @PreAuthorize("@ss.hasPermi('manage:appointment:confirm')")
    @Log(title = "批量确认预约", businessType = BusinessType.UPDATE)
    @PutMapping("/batchConfirm")
    public AjaxResult batchConfirmAppointments(@RequestBody Map<String, Object> params)
    {
        Long[] appointmentIds = ((List<Long>) params.get("appointmentIds")).toArray(new Long[0]);
        Long clubId = getUserId();
        
        int successCount = crInterviewAppointmentService.batchConfirmAppointments(appointmentIds, clubId);
        return success("成功确认 " + successCount + " 个预约");
    }

    /**
     * 根据学生ID查询预约列表
     */
    @PreAuthorize("@ss.hasPermi('manage:appointment:list')")
    @GetMapping("/student/{studentId}")
    public AjaxResult getAppointmentsByStudent(@PathVariable Long studentId)
    {
        List<CrInterviewAppointment> appointments = crInterviewAppointmentService.selectAppointmentsByStudentId(studentId);
        return success(appointments);
    }

    /**
     * 根据社团ID查询预约列表
     */
    @PreAuthorize("@ss.hasPermi('manage:appointment:list') or @ss.hasRole('club')")
    @GetMapping("/club/{clubId}")
    public AjaxResult getAppointmentsByClub(@PathVariable Long clubId)
    {
        List<CrInterviewAppointment> appointments = crInterviewAppointmentService.selectAppointmentsByClubId(clubId);
        return success(appointments);
    }

    /**
     * 根据面试时段ID查询预约列表
     */
    @PreAuthorize("@ss.hasPermi('manage:appointment:list')")
    @GetMapping("/slot/{slotId}")
    public AjaxResult getAppointmentsBySlot(@PathVariable Long slotId)
    {
        List<CrInterviewAppointment> appointments = crInterviewAppointmentService.selectAppointmentsBySlotId(slotId);
        return success(appointments);
    }

    /**
     * 检查学生是否有时间冲突
     */
    @GetMapping("/checkConflict/student")
    public AjaxResult checkStudentTimeConflict(@RequestParam Long studentId, @RequestParam Long slotId)
    {
        boolean hasConflict = crInterviewAppointmentService.checkStudentTimeConflict(studentId, slotId);
        return success(hasConflict);
    }

    /**
     * 检查面试官是否有时间冲突
     */
    @GetMapping("/checkConflict/interviewer")
    public AjaxResult checkInterviewerTimeConflict(@RequestParam Long interviewerId, @RequestParam Long slotId)
    {
        boolean hasConflict = crInterviewAppointmentService.checkInterviewerTimeConflict(interviewerId, slotId);
        return success(hasConflict);
    }

    /**
     * 获取学生的预约统计
     */
    @PreAuthorize("@ss.hasPermi('manage:appointment:list')")
    @GetMapping("/statistics/student/{studentId}")
    public AjaxResult getStudentAppointmentStatistics(@PathVariable Long studentId)
    {
        Map<String, Object> statistics = crInterviewAppointmentService.getStudentAppointmentStatistics(studentId);
        return success(statistics);
    }

    /**
     * 获取社团的预约统计
     */
    @PreAuthorize("@ss.hasPermi('manage:appointment:list')")
    @GetMapping("/statistics/club/{clubId}")
    public AjaxResult getClubAppointmentStatistics(@PathVariable Long clubId)
    {
        Map<String, Object> statistics = crInterviewAppointmentService.getClubAppointmentStatistics(clubId);
        return success(statistics);
    }

    /**
     * 获取面试时段的预约统计
     */
    @PreAuthorize("@ss.hasPermi('manage:appointment:list')")
    @GetMapping("/statistics/slot/{slotId}")
    public AjaxResult getSlotAppointmentStatistics(@PathVariable Long slotId)
    {
        Map<String, Object> statistics = crInterviewAppointmentService.getSlotAppointmentStatistics(slotId);
        return success(statistics);
    }

    /**
     * 查询需要提醒的预约
     */
    @PreAuthorize("@ss.hasPermi('manage:appointment:list')")
    @GetMapping("/reminders")
    public AjaxResult getAppointmentsForReminder(@RequestParam(defaultValue = "2") int hours)
    {
        List<CrInterviewAppointment> appointments = crInterviewAppointmentService.getAppointmentsForReminder(hours);
        return success(appointments);
    }

    /**
     * 发送预约提醒
     */
    @PreAuthorize("@ss.hasPermi('manage:appointment:remind')")
    @PostMapping("/remind/{appointmentId}")
    public AjaxResult sendAppointmentReminder(@PathVariable Long appointmentId)
    {
        return toAjax(crInterviewAppointmentService.sendAppointmentReminder(appointmentId));
    }

    /**
     * 批量发送预约提醒
     */
    @PreAuthorize("@ss.hasPermi('manage:appointment:remind')")
    @PostMapping("/batchRemind")
    public AjaxResult batchSendReminders(@RequestBody Long[] appointmentIds)
    {
        int successCount = crInterviewAppointmentService.batchSendReminders(appointmentIds);
        return success("成功发送 " + successCount + " 条提醒");
    }

    /**
     * 查询过期未处理的预约
     */
    @PreAuthorize("@ss.hasPermi('manage:appointment:list')")
    @GetMapping("/expired")
    public AjaxResult getExpiredAppointments()
    {
        List<CrInterviewAppointment> appointments = crInterviewAppointmentService.getExpiredAppointments();
        return success(appointments);
    }

    /**
     * 自动处理过期预约
     */
    @PreAuthorize("@ss.hasPermi('manage:appointment:edit')")
    @PutMapping("/processExpired")
    public AjaxResult processExpiredAppointments()
    {
        int processedCount = crInterviewAppointmentService.processExpiredAppointments();
        return success("处理了 " + processedCount + " 个过期预约");
    }
}